'use strict'

/*   初时Babel
     

*/

const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const types = require('@babel/types')
const generator = require('@babel/generator').default;

let code = `
    let a =1, b = 2;
    function sum(a, b){
        return a + b;
    }
    sum(a, b);`

/*  前序操作:
    工具：parser
    输入：源码
    输出：AST
*/
let ast = parser.parse(code)
// console.log(ast.program)
// console.log(Object.keys(ast.program), typeof ast.program.__proto__, Object.getOwnPropertyNames(ast.program))
// console.log(JSON.stringify(ast, null, '\t'))

/*  中序操作：
    工具：traverse
    输入：AST，visitor
    输出：null（原地修改AST）

*/
let visitor = {
    Program: {
        enter: function(path){
            console.log('enter'+path.node.type)
            console.log(path.container)
        },
        exit: function(path){
            // console.log(path)
            console.log('exit'+path.node.type)
        }
    },

    FunctionDeclaration: {
        enter: function(path){
            // console.log(path.node.type)
            // 当进入到FunctionDeclaration节点时，替换其函数名 sum -> add
            console.log('enter'+path.node.type)
            let idf_path = path.get('id')
            if (idf_path.node.name == 'sum'){
                console.log('000000000000000000000000000000000000000000')
                idf_path.replaceWith(types.identifier('add'))
            }
            console.log(path.container)
        },
        exit: function(path){
            // console.log(path)
            console.log('exit'+path.node.type)
        }
    },

    VariableDeclarator: {
        enter: function(path){
            console.log('enter'+path.node.type)
            console.log(path.container)
        },
        exit: function(path){
            // console.log(path)
            console.log('exit'+path.node.type)
        }
    },

    ExpressionStatement: {
        enter: function(path){
            console.log('enter'+path.node.type)
            console.log(path.container)
        },
        exit: function(path){
            // console.log(path)
            console.log('exit'+path.node.type)
        }
    }
}

traverse(ast, visitor)

/*  后续操作
    工具：generator
    输入：AST
    输出：转换后的代码
*/
let {code} = generator(ast)

console.log(code)
